package com.xhdx;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DateUtil {
	/** yyyyMMdd **/
	public static final String DATE_PATTERN = "yyyyMMdd";
	/** yyyy-MM-dd HH:mm:ss **/
	public static final String DATE_TIME_PATTERN = "yyyy-MM-dd HH:mm:ss";
	/** yyyyMMddHHmmss **/
	public static final String DATE_TIME_SHORT_PATTERN = "yyyyMMddHHmmss";
	/** yyyy-MM-dd **/
	public static final String DATE_STANDARD_PATTERN = "yyyy-MM-dd";
	public static final String[] PARSE_PATTERNS = new String[] { DATE_TIME_SHORT_PATTERN, DATE_PATTERN,
			DATE_STANDARD_PATTERN, DATE_TIME_PATTERN };

	private static SimpleDateFormat yyyyMMddHHmmssssssss = new SimpleDateFormat(DATE_TIME_SHORT_PATTERN);

	private static Map<String, SimpleDateFormat> sdfMap = new HashMap<String, SimpleDateFormat>();

	public static SimpleDateFormat getSimpleDateFormat(String format) {
		if (sdfMap.get(format) == null) {
			SimpleDateFormat sdf = new SimpleDateFormat(format);
			sdfMap.put(format, sdf);
		}

		return sdfMap.get(format);
	}

	/**
	 * 返回指定格式当前系统时间
	 */
	public static String getCurrDate(String format) {
		return getSimpleDateFormat(format).format(System.currentTimeMillis());
	}

	/**
	 * 返回指定格式当前系统时间 yyyyMMdd
	 */
	public static String getCurrDate() {
		return getCurrDate(DATE_PATTERN);
	}

	/**
	 * 获得当前时间+6位随机数 格式：yyyyMMddHHmmssssssss
	 *
	 * @return String
	 */
	public static String getCurrentTime() {
		Random random = new Random();
		StringBuilder result = new StringBuilder();
        int digit=6;
        for (int i = 0; i < digit; i++) {
            result.append(random.nextInt(10));
        }


		return yyyyMMddHHmmssssssss.format(new Date()) +result;
	}

	/**
	 * 计算d2-d1之间的天数
	 */
	public static int getDaysBetween(Calendar d1, Calendar d2) {
		int days = (int) getDays(d1.getTime(), d2.getTime());

		return days;
	}

	/**
	 * 计算d2-d1之间的天数
	 */
	public static int getDaysBetween(String d1, String d2) {
		return getDaysBetween(covertCalendar(d1), covertCalendar(d2));
	}

	
	/**
	 * 得到当前日期加上aMonths月后的日期.
	 * 
	 * @param aMonths
	 *            大于0时将加上该月数求之后几月的日期，小于0时将减去该月数求之前几月的日期
	 * @return
	 */
	public static String getAfterMonthDate(int aMonths) {
		return getAfterMonthDate(getCurrDate(), aMonths);
	}

	/**
	 * 得到传入日期加上aMonths月后的日期.
	 * 
	 * @param date
	 *            传入日期
	 * @param aMonths
	 *            大于0时将加上该月数求之后几月的日期，小于0时将减去该月数求之前几月的日期
	 * @return
	 */
	public static String getAfterMonthDate(String date, int aMonths) {
		SimpleDateFormat fmt = getSimpleDateFormat(DATE_PATTERN);
		Date theDate = null;
		java.util.Calendar cal = Calendar.getInstance();

		try {
			theDate = fmt.parse(date);
		} catch (ParseException e) {
//			/logger.error(e.getMessage());
		}

		cal.setTime(theDate);
		cal.add(Calendar.MONTH, aMonths);

		return fmt.format(cal.getTime());
	}

	/**
	 * 获取月份最后日期
	 * 
	 * @param date
	 * @return
	 * @throws ParseException
	 */
	public static String getMaxMonthDate(String date) {
		Calendar calendar = covertCalendar(date);
		calendar.set(Calendar.DAY_OF_MONTH, calendar.getActualMaximum(Calendar.DAY_OF_MONTH));

		return formatDate(calendar);
	}

	/**
	 * 计算两个日期之间的天数
	 * 
	 * @param aStartDate
	 * @param aEndDate
	 * @return long
	 */
	public static final long getDays(Date startDate, Date endDate) {
		return ((endDate.getTime() / (24 * 60 * 60 * 1000)) - (startDate.getTime() / (24 * 60 * 60 * 1000)));
	}

	public static Date convertDate(String date) {
		return convertDate(date, DATE_PATTERN);
	}

	public static Date convertDate(String date, String dateFormat) {
		SimpleDateFormat sdf = getSimpleDateFormat(dateFormat);

		try {
			return sdf.parse(date);
		} catch (ParseException e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * 将日期转为String
	 * 
	 * @param date
	 * @return
	 */
	public static String formatDate(Date date, String formate) {
		return getSimpleDateFormat(formate).format(date);
	}

	/**
	 * 将日期转为String
	 * 
	 * @param date
	 * @return
	 */
	public static String formatDate(Date date) {
		return formatDate(date, DATE_PATTERN);
	}

	/**
	 * 将Calendar转为String
	 * 
	 * @param cal
	 * @return
	 */
	public static String formatDate(Calendar cal) {
		return getSimpleDateFormat(DATE_PATTERN).format(cal.getTime());
	}

	/**
	 * 将String 转为 Calendar
	 */
	public static Calendar covertCalendar(String str) {
		Calendar calendar = Calendar.getInstance();
		int aYear = new Integer(str.substring(0, 4)).intValue();
		int aMonth = new Integer(str.substring(4, 6)).intValue();
		int aDay = new Integer(str.substring(6, 8)).intValue();
		calendar.set(Calendar.YEAR, aYear);
		calendar.set(Calendar.MONTH, aMonth - 1);
		calendar.set(Calendar.DAY_OF_MONTH, aDay);

		return calendar;
	}

	/**
	 * 得到当前日期加上aDates天后的日期.
	 * 
	 * @param aDates
	 *            大于0时将加上该天数求之后几天的日期，小于0时将减去该天数求之前几天的日期
	 * @return
	 */
	public static String getAfterDate(int aDates) {
		return getAfterDate(getCurrDate(), aDates);
	}

	/**
	 * 得到传入日期加上adates后的日期.
	 * <p>
	 * 
	 * @param date1
	 * @param adates
	 * @return
	 */
	public static String getAfterDate(String date1, int adates) {
		SimpleDateFormat fmt = getSimpleDateFormat("yyyyMMdd");
		Date theDate = null;
		java.util.Calendar cal = Calendar.getInstance();

		try {
			theDate = fmt.parse(date1);
		} catch (ParseException e) {
			e.printStackTrace();
		}

		cal.setTime(theDate);
		cal.add(Calendar.DATE, adates);

		return fmt.format(cal.getTime());
	}

	/**
	 * 得到传入日期加上adates后的日期.
	 * <p>
	 * 
	 * @param date1
	 * @param adates
	 * @return
	 */
	public static String getAfterDate(String date1, int adates, String format) {
		SimpleDateFormat fmt = getSimpleDateFormat(format);
		Date theDate = null;
		java.util.Calendar cal = Calendar.getInstance();

		try {
			theDate = fmt.parse(date1);
		} catch (ParseException e) {
			e.printStackTrace();
		}

		cal.setTime(theDate);
		cal.add(Calendar.DATE, adates);

		return fmt.format(cal.getTime());
	}

	/**
	 * 计算出两个日期之间相差的天数 建议date1 大于 date2 这样计算的值为正数
	 * 
	 * @param date1
	 *            日期1
	 * @param date2
	 *            日期2
	 * @return date1 - date2
	 */
	public static int dateInterval(long date1, long date2) {
		return (int) ((date1 - date2) / (24 * 60 * 60 * 1000));
	}

	/**
	 *
	 * 描述:日期含时分秒格式校验：yyyyMMddHHmmss param verifyDate 校验日期 return true
	 * 校验格式正确，false 校验格式错误
	 */
	public static boolean checkDate(String verifyDate) {
		String date = verifyDate.substring(0, 4);
		date += "-";
		date += verifyDate.substring(4, 6);
		date += "-";
		date += verifyDate.substring(6, 8);
		date += " ";
		date += verifyDate.substring(8, 10);
		date += "-";
		date += verifyDate.substring(10, 12);
		date += "-";
		date += verifyDate.substring(12, 14);

		// 判断年月日的正则表达式，接受输入格式为yyyy-MM-dd HH-mm-ss ，可接受平年闰年的日期
		String expDate = "^((([0-9]{3}[1-9]|[0-9]{2}[1-9][0-9]{1}|[0-9]{1}[1-9][0-9]{2}|[1-9][0-9]{3})-(((0[13578]|1[02])-(0[1-9]|[12][0-9]|3[01]))|((0[469]|11)-(0[1-9]|[12][0-9]|30))|(02-(0[1-9]|[1][0-9]|2[0-8]))))|((([0-9]{2})(0[48]|[2468][048]|[13579][26])|((0[48]|[2468][048]|[3579][26])00))-02-29))\\s+([0-1]?[0-9]|2[0-3])-([0-5][0-9])-([0-5][0-9])$";
		Pattern p = Pattern.compile(expDate);
		Matcher m = p.matcher(date);

		return m.matches();
	}

	/**
	 * 将日期类型的字符串由一种形式转换为另一种形式
	 * 
	 * @param org
	 *            日期字符串
	 * @param orgPatten
	 *            org日期字符串的格式
	 * @param toPattern
	 *            需要展现的格式 例如：需要将20170615101700转化成2017-06-15 10:17:00 则相应参数为：
	 *            org:20170615101700,orgPatten:yyyyMMddHHmmss,toPattern:yyyy-MM-
	 *            dd HH:mm:ss
	 * @return 转换后的字符串
	 */
	public static String formatDateString(String org, String orgPatten, String toPattern) {
		SimpleDateFormat sdf = new SimpleDateFormat(orgPatten);
		SimpleDateFormat fmt = new SimpleDateFormat(toPattern);
		String afterFmt = "";
		try {
			Date date = sdf.parse(org);
			afterFmt = fmt.format(date);
		} catch (ParseException e) {
			return org;
		}
		return afterFmt;
	}

	/**
	 * 获取当前日期是星期几<br>
	 * 
	 * @param dt
	 * @return 当前日期是星期几
	 */
	public static String getWeekOfDate(String date1) {
		String[] weekDays = { "7", "1", "2", "3", "4", "5", "6" };
		Calendar cal = covertCalendar(date1);

		int w = cal.get(Calendar.DAY_OF_WEEK) - 1;
		if (w < 0) {
			w = 0;
		}
		return weekDays[w];
	}

	public static void main(String[] args) {
		/*
		 * String org = "20170615"; String orgPatten = "yyyyMMddHHmmss"; String
		 * toPatten = "yyyy-MM-dd HH:mm:ss"; String afterFmt =
		 * formatDateString(org,orgPatten,toPatten);
		 * System.out.println(afterFmt); System.out.println(getCurrentTime());
		 */

		String x = getWeekOfDate("20170903");
		System.out.println(x);
	}
	
}
